package filex

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logc"
	"os"
	"time"
)

type FileWriter struct {
	messages chan string
	ticker   *time.Ticker

	file *os.File
}

func NewFileWriter(internal int64) (result *FileWriter, err error) {
	result = &FileWriter{
		messages: make(chan string),
	}

	// 打开文件
	result.file, err = os.OpenFile("portal_business.log", os.O_CREATE|os.O_APPEND|os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		return result, err
	}

	// 启动定时器
	//result.ticker = time.NewTicker(time.Duration(internal) * time.Second)

	return
}
func (f *FileWriter) Write(message string) {
	go func() {
		f.messages <- message
	}()
}
func (f *FileWriter) StartListening() {
	for {
		select {
		case message := <-f.messages:
			_, err := f.file.WriteString(fmt.Sprintf("%s\n", message))
			if err != nil {
				logc.Error(context.TODO(), "write to log file fail,err:", err.Error())
			}
			//case <-f.ticker.C:
			//	f.file.Truncate(0)
			//	return
		}
	}
}
